﻿namespace Avatar.Controls
{
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Input;
    using System.Windows.Media;
    using System;

    [TemplatePart(Name = ContentContainer, Type = typeof(Grid))]
    public class PullListItem : ContentControl
    {
        public const string ContentContainer = "ContentContainer";

        Grid contentContainer;

        PullList parent;

        public override void OnApplyTemplate()
        {
            parent = GetParentPulllist();

            if (contentContainer != null)
            {
                contentContainer.ManipulationStarted -= ScrollViewer_ManipulationStarted;
                contentContainer.ManipulationCompleted -= ScrollViewer_ManipulationCompleted;
            }

            contentContainer = base.GetTemplateChild(ContentContainer) as Grid;

            base.OnApplyTemplate();

            if (contentContainer != null)
            {
                contentContainer.ManipulationStarted += ScrollViewer_ManipulationStarted;
                contentContainer.ManipulationCompleted += ScrollViewer_ManipulationCompleted;
            }
        }

        /// <summary>
        /// Initializes a new instance of the PullListItem class.
        /// </summary>
        public PullListItem()
        {
            DefaultStyleKey = typeof(PullListItem);
        }

        private void ScrollViewer_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
            if (ManipulationStateChanged != null)
            {
                //System.Threading.ThreadPool.QueueUserWorkItem(o =>
                //{
                    ManipulationStateChanged(this, new ManipulationActionEventArgs(ManipulationAction.Started));
                //});
            }
        }

        private void ScrollViewer_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
        {
            if (ManipulationStateChanged != null)
            {
                //System.Threading.ThreadPool.QueueUserWorkItem(o =>
                //{
                    ManipulationStateChanged(this, new ManipulationActionEventArgs(ManipulationAction.Completed));
                //});
            }
        }

        private PullList GetParentPulllist()
        {
            var p = VisualTreeHelper.GetParent(this);

            while (!(p is PullList) && (p != null))
            {
                p = VisualTreeHelper.GetParent(p as DependencyObject);
            }

            return p as PullList;
        }

        #region input events
        internal event EventHandler<ManipulationActionEventArgs> ManipulationStateChanged;
        #endregion
    }
}
